package com.example.eddie.test.activity;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.example.eddie.test.ConnectionWeb.Connection;
import com.example.eddie.test.MyAdapter.InfoAdapter;
import com.example.eddie.test.MyDatabases.MyDatabaseHelper;
import com.example.eddie.test.PoJo.TeacherClassInfo;
import com.example.eddie.test.R;
import com.example.eddie.test.Util.JsoupHtmlUtil;
import com.rengwuxian.materialedittext.MaterialAutoCompleteTextView;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.rengwuxian.materialedittext.MaterialMultiAutoCompleteTextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.IDN;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

public class GetTeacherClass extends AppCompatActivity {

    private MaterialAutoCompleteTextView mAutoTextview;
    private MaterialEditText EditText_verification;
    private ImageView imgView;
    private ListView ListInfo;

    private LinearLayout yzm_linear;

    private Connection connection;
    private JsoupHtmlUtil HtmlUtil = new JsoupHtmlUtil();

    private InfoAdapter infoAdapter;

    private MyDatabaseHelper database;
    private SQLiteDatabase writableDatabase;

    private List<TeacherClassInfo> list = new ArrayList<>();
    private String[] day = new String[]{"星期一","星期二","星期三","星期四","星期五","星期六","星期日"};
    private String[] time = new String[]{"第一节","第二节","第三节","第四节","晚上(第五节)"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_get_teacher_class);

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        initView();
        setImgView();
        getNameInfo();
        List<String> list = initName();

        ArrayAdapter adapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,list);
        mAutoTextview.setAdapter(adapter);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    private void initView(){
        mAutoTextview = (MaterialAutoCompleteTextView) findViewById(R.id.EditText_name);
        EditText_verification = (MaterialEditText) findViewById(R.id.EditText_verification);

        imgView = (ImageView) findViewById(R.id.view_img);
        imgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setImgView();
            }
        });

        ListInfo = (ListView) findViewById(R.id.list_Info);
        yzm_linear = (LinearLayout) findViewById(R.id.yzm_linear);
        database = new MyDatabaseHelper(this,"SearchInfo.db",null,1);
        writableDatabase = database.getWritableDatabase();
        infoAdapter = new InfoAdapter(getApplicationContext(),R.layout.teacher_layout,list);
        ListInfo.setAdapter(infoAdapter);
        connection = new Connection();
    }

    public void button_get(View view) {
        String teacherName = mAutoTextview.getText().toString();
        String yzm = EditText_verification.getText().toString();

        if (!teacherName.equals("")) {

            if (!yzm.equals("")) {

                button_getInfo(teacherName,yzm);

            } else {

                Toast.makeText(this, "请输入验证码！", Toast.LENGTH_SHORT).show();

            }

        }else {

            Toast.makeText(this, "请输入教师姓名！", Toast.LENGTH_SHORT).show();

        }
    }

    private void button_getInfo(final String teacherName,final String yzm){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Cursor cursor = writableDatabase.query("TeacherInfo",null,"teacherName like ?",new String[]{teacherName},null,null,null);
                    if (cursor.getCount()!=0){
                        cursor.moveToFirst() ;
                        String ID = cursor.getString(2);
                        String string = connection.getString("http://59.79.112.9/ZNPK/TeacherKBFB_rpt.aspx", "http://59.79.112.9/ZNPK/TeacherKBFB.aspx", ID, yzm);
                        JsoupData(string);
                    }else {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(), "请输入正确的教师姓名", Toast.LENGTH_LONG).show();
                            }
                        });
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void JsoupData(String HtmlData){
        String td = Jsoup.parse(HtmlData).select("td").text();

        if (HtmlData.contains("验证码错误！")){
            showToast("Wops~ 验证码错误!");

            resetListView();

            setImgView();

        }else if (td.equals("")){
            showToast("Wops~ 老师，您没有课哦～");
            resetListView();
            setImgView();

        }else {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    yzm_linear.setVisibility(View.GONE);
                }
            });
            formartDate(HtmlData);
        }
    }

    private void resetListView(){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                list.clear();
                infoAdapter.notifyDataSetChanged();
            }
        });
    }

    private void formartDate(String HtmlData){
        list.clear();

        String[][] table = HtmlUtil.jsoup(HtmlData);
        String thisTime1;
        String thisTime2;
        TeacherClassInfo teacherClassInfo = null;

        for(int x = 0;x<table.length;x++){
            for(int y = 0;y<table[x].length;y++){
                teacherClassInfo = null;
                String s = table[x][y];
                if (!s.equals("")) {
                    String data = day[y];
                    if (x <= 2) {
                        thisTime1 = "上午";
                        thisTime2 = time[x];
                    } else {
                        thisTime1 = "下午";
                        thisTime2 = time[x];
                    }
                    teacherClassInfo = new TeacherClassInfo(s, thisTime1, thisTime2, data,y);
                }

                if (teacherClassInfo!=null) {
                    list.add(teacherClassInfo);
                }

                sort(list);
            }
        }
    }

    private void showToast(final String text){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
                yzm_linear.setVisibility(View.VISIBLE);
            }
        });
    };

    private void sort(List list){
        HtmlUtil.sort(list);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                infoAdapter.notifyDataSetChanged();
            }
        });
    }

    private void getNameInfo(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                Cursor cursor = writableDatabase.query("TeacherInfo", null, null, null, null, null, null);
                final List<String> list = new ArrayList<>();
                if (cursor.moveToFirst()){
                    do {
                        list.add(cursor.getString(cursor.getColumnIndex("teacherName")));
                    }while (cursor.moveToNext());
                }

                insertDatabases(list);
            }
        }).start();
    }

    private void insertDatabases(List<String> list){
        try {
            Document doc= Jsoup.connect("http://59.79.112.9/ZNPK/Private/List_JS.aspx?xnxq=20170&t=").timeout(5000).get();
            Elements os = doc.select("script");
            String[] elect = os.toString().split("'");
            Elements elements = Jsoup.parse(elect[1]).select("option");
            List<Element> listName = elements.subList(0,elements.last().elementSiblingIndex());

            for (int i = 0; i < elements.last().elementSiblingIndex(); i++) {
                String s = listName.get(i).toString();
                String[] split = s.split(">");
                String[] split1 = split[1].split("<");
                Element ele = listName.get(i);
                if (!list.contains(split1[0])){
                    String value = "teacherID?" + ele.attr("value");
                    ContentValues values = new ContentValues();
                    values.put("teacherName", split1[0]);
                    values.put("teacherID", value);
                    writableDatabase.insert("TeacherInfo", null, values);
                    values.clear();
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void setImgView(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                final Bitmap bitmap = connection.initImg("http://59.79.112.9/sys/ValidateCode.aspx","http://59.79.112.9/ZNPK/TeacherKBFB.aspx");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        imgView.setImageBitmap(bitmap);
                    }
                });
            }
        }).start();
    }

    private List<String> initName(){
        List<String> name = new ArrayList<>();
        Cursor cursor = writableDatabase.query("TeacherInfo", null, null, null, null, null, null);
        if (cursor.moveToFirst()){
            do {
                String teacher = cursor.getString(cursor.getColumnIndex("teacherName"));
                name.add(teacher);
            }while (cursor.moveToNext());
        }

        return name;
    }

}
